package myJs.basic344

import myJs.Implicits._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.{Element, document}
import slinky.web.ReactDOM

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.annotation._

@JSExportTopLevel("Basic344Detail")
object Basic344Detail {
  var geneId = ""

  @JSExport("init")
  def init(id: String,h2:Boolean) = {
    geneId = id
    refreshBySpecies
    registerEvent
    ReactDOM.render(ExpCp(id,h2), document.querySelector("#root"))
  }

  def registerEvent = {
    $(document.body).on("click", s".myDownloadCds", "", (y: Element) => {
      downloadCds
    })
    $(document.body).on("click", s".myDownloadPep", "", (y: Element) => {
      downloadPep
    })
  }

  def downloadCds = {
    val fileName = "cds.fa"
    val seqText = $("#cds").text().trim
    val content = List(s">${geneId}", seqText).mkString("\n")
    Tool.downloadTxt(fileName, content)
  }

  def downloadPep = {
    val fileName = "pep.fa"
    val seqText = $("#pep").text().trim
    val content = List(s">${geneId}", seqText).mkString("\n")
    Tool.downloadTxt(fileName, content)
  }

  def refreshBySpecies = {
    val url = g.jsRoutes.controllers.Basic344Controller.basicInfo().url.toString
    Ajax.get(url = s"${url}?geneId=${geneId}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      val species = rs.myGet("species")
      val loc = s"${rs.myGet("chr")}:${rs.myGet("start")}..${rs.myGet("end")}"
      val src = species match {
        case _ =>
          s"http://47.92.172.28:8080/?data=my_data/nut/minteg_2022/data&loc=${loc}&tracks=DNA,Annotation&tracklist=0&nav=1&overview=0"

      }
      $("#jBrowse").attr("src", src)
    }
  }
}
